package com.summerli.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.summerli.common.ResponseResult;
import com.summerli.common.sms.SmsSendRequest;
import com.summerli.common.sms.SmsTemplateDto;
import com.summerli.constant.SmsStatusEnum;
import com.summerli.dao.entity.ServiceSmsRecord;
import com.summerli.dao.entity.ServiceSmsTemplate;
import com.summerli.dao.mapper.ServiceSmsRecordMapper;
import com.summerli.dao.mapper.ServiceSmsTemplateMapper;
import com.summerli.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class SmsServiceImpl  implements SmsService {
    private ConcurrentHashMap<String,String> smsTemplateMap = new ConcurrentHashMap<>();
    @Autowired
    private ServiceSmsRecordMapper smsRecordMapper;

    @Autowired
    private ServiceSmsTemplateMapper templateMapper;
    @Override
    public ResponseResult sendSms(SmsSendRequest smsSendRequest) {
        //使用缓存，缓存短信模板
        if(smsSendRequest != null){
            String[] receivers = smsSendRequest.getReceivers();
            for (String receiver:
                    receivers) {
                ServiceSmsRecord record = new ServiceSmsRecord();
                record.setPhoneNumber(receiver);
                List<SmsTemplateDto> smsTemplateDtos = smsSendRequest.getData();
                for (SmsTemplateDto smsTemplate:
                        smsTemplateDtos) {
                    String id = smsTemplate.getId();
                    if(!smsTemplateMap.containsKey(id)){
                        // 查询数据库
                        ServiceSmsTemplate serviceSmsTemplate = templateMapper.selectByTemplateId(smsTemplate.getId());
                        smsTemplateMap.put(id, serviceSmsTemplate.getContent());
                    }
                    String content = smsTemplateMap.get(id);
                    for (Map.Entry<String,Object> entry:
                    smsTemplate.getTemplateMap().entrySet()) {
                        content = StringUtils.replace(content, "${" + entry.getKey() + "}", "" + entry.getValue());
                    }

                    //发送成功的短信，插入数据的操作
                    try{
                        int result = send(receiver, smsTemplate.getId(), smsTemplate.getTemplateMap());
                        record.setSmsContent(content);
                        record.setSendTime(new Date());
                        record.setOperator("");
                        record.setSendFlag(true);
                        record.setSendNumber(true);
                        if (result != SmsStatusEnum.SEND_SUCCESS.getCode()) {
                            throw new Exception("短信发送失败");
                        }
                    }catch (Exception e){
                        record.setSendFlag(false);
                        record.setSendNumber(false);
                        log.error("发送短信（" + id + "）失败：" + receiver, e);
                    }finally {
                        record.setCreateTime(new Date());
                        smsRecordMapper.insert(record);
                        return ResponseResult.success("");
                    }
                }
            }
        }
        return ResponseResult.fail(-1, "无效请求!!");
    }

    private int send(String phoneNumber, String templateId, Map<String, ?> map) throws Exception {
        JSONObject param = new JSONObject();
        param.putAll(map);

        return sendMsg(phoneNumber, templateId, param.toString());
    }

    private int sendMsg(String phoneNumber, String templateCode, String param) {

        /**
         *  供应商 发 短信
         */
        return SmsStatusEnum.SEND_FAIL.getCode();

    }
}
